/**
 * 
 */
package fr.toto.menuitem;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.file.Path;

import javax.swing.JMenuItem;

import com.kokotchy.betaSeriesAPI.model.Episode;

import fr.toto.exceptions.ProcessException;
import fr.toto.files.AccesFile;
import fr.toto.script.ScriptLancher;
import fr.toto.triseries.Regex;

/**
 * @author tshepo
 * 
 */
public class ScriptMenuItem extends JMenuItem {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2107243893075273905L;
	private String cmd;

	public ScriptMenuItem(Episode ep, String name, final String pgm, String args) {
		super(name);

		cmd = Regex.printEpisode(ep, args);
		if (args.contains("{FILE}") || args.contains("{FILEDIR}") || args.contains("{FILENAME}") || args.contains("{FILEBASENAME}")) {
			Path file = AccesFile.Find(ep);
			if (file == null) {
				this.setEnabled(false);
				return;
			}
			cmd = cmd.replace("{FILE}", file.toString());
			cmd = cmd.replace("{FILEDIR}", file.getParent().toString());
			cmd = cmd.replace("{FILENAME}", file.getFileName().toString());
			cmd = cmd.replace("{FILEBASENAME}", file.getFileName().toString().substring(0, file.getFileName().toString().lastIndexOf(".")));
		}

		this.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					new ScriptLancher(pgm,cmd);
				} catch (Exception e1) {
					new ProcessException(e1);
				}

			}
		});
	}

}
